package middleware

import (
	"go-gin/common"
	"go-gin/model"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

//中间件

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从请求头中获取token即获取authoriazation的header
		tokenString := c.GetHeader("Authorization")

		//验证格式，是否为空或以Bearer
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") { //检查token是否以"Bearer "开头，！最后有个空格 是六位！
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "token格式错误"})
			c.Abort() //抛弃请求，阻止执行
			return
		}

		//因为以Bearer 开头所以有效是从第七位
		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "token解析失败"})
			c.Abort()
			return
		}

		//验证通过后获得claims里的user.ID
		userId := claims.UserId
		db := common.GetDB()
		var user model.User
		db.First(&user, userId)

		//验证用户是否存在
		if user.ID == 0 {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "用户不存在"})
			c.Abort()
			return
		}

		//用户存在
		c.Set("user",user)
		c.Next()
	}
}
